<?php
	defined('INDEX') or die ('Acesso direto n&atilde;o permitido');
	
	class PageAccessControl
	{
		public function __construct ()
		{
			
		}
		
		/**
		 * This function returns an instance of FormularioBase object.
		 * 
		 * @param string $pagename - the name of page
		 * 
		 * @return FormularioBase $form - an instance of FormularioBase based on 
		 * requested page.
		 */
		public function getPage ($pagename)
		{
			if($pagename != '')
			{
				require_once (dirname(__FILE__)."/../application/ApplicationFactory.class.php");
				
				$connection = ApplicationFactory::getDoctrineConnectionFactory();
				
				$table = Doctrine::getTable('Pagina');
				
				$pagina = $table->findBy('nome', $pagename)->getFirst();
				
				if(isset($pagina))
				{
					if($pagina->status != 'A')
					{
						$content = new stdClass();
						
			            $content->type        = 3;
			            $content->mensagem    = "A página requisitada não está ativa no sistema.";
			            $content->title       = "Página Inativa";
			            
			            ApplicationFactory::getSessionFactory()->storeMessage($content);
			            
			            return $this->getPage('home');
					}
					else
					{
						$classPath = dirname(__FILE__)."/../../gui/".$pagina->arquivo;
						
						if(file_exists($classPath) && !is_dir($classPath))
						{
							require_once ($classPath);
							
							$className = str_replace(".class.php", "", $pagina->arquivo);
							
							if(class_exists($className))
							{
								$form = new $className($pagina);
								
								return $form;
							}
							else
							{
								return null;
							}
						}
						else
						{
							return null;
						}
					}
				}
				else
				{
					$content = new stdClass();
					
		            $content->type        = 3;
		            $content->mensagem    = "A página requisitada não existe.";
		            $content->title       = "Página não encontrada";
		            
		            ApplicationFactory::getSessionFactory()->storeMessage($content);
		            
		            return $this->getPage('home');
				}
			}
			else
			{
				return null;
			}
		}
		
		/**
		 * This method checks if the requested class page exists in the database.
		 * 
		 * @param string $pagename - the name of page.
		 * 
		 * @return bool - true when exists and false if not exists.
		 */
		public function hasPage ($pagename)
		{
			if($pagename != '')
			{
				require_once (dirname(__FILE__)."/../application/ApplicationFactory.class.php");
				
				$connection = ApplicationFactory::getDoctrineConnectionFactory();
				
				$table = Doctrine::getTable('Pagina');
				
				$pagina = $table->findBy('nome', $pagename)->getFirst();
				
				if($pagina)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
	}
?>